package ian.swing;

import java.util.*;

import org.jbpm.api.*;
import org.jbpm.api.task.Task;

public class MyProcessEngine {
	
	static private MyProcessEngine mpe;
	
	public static MyProcessEngine getProcessEngineInstance(){
		if(mpe == null)
			mpe = new MyProcessEngine();
		return mpe;
	}

	private ProcessEngine pe;
	private RepositoryService rs;
	private ExecutionService es;
	private TaskService ts;
	private String deployId;
	
	private MyProcessEngine(){
		pe = Configuration.getProcessEngine();
		rs = pe.getRepositoryService();
		es = pe.getExecutionService();
		ts = pe.getTaskService();
		deployId = rs.createDeployment().addResourceFromClasspath("leave.jpdl.xml").deploy();
	}
	
	public String getTaskVar(String taskId, String varName){
		return ts.getVariable(taskId, varName).toString();
	}
	
	public void startProcess(String user){
		Map map = new HashMap();
		map.put("user", user);
		es.startProcessInstanceByKey("leave",map);
	}
	
	public void submitTask(String taskId, int dayOff, String reason){
		Map map = new HashMap();
		map.put("dayOff",dayOff);
		map.put("reason", reason);
		ts.completeTask(taskId, map);
	}
	
	public void examineTask(boolean isApproval, String taskId){
		if(isApproval)
			ts.completeTask(taskId, "approve");
		else
			ts.completeTask(taskId, "reject");
	}
	
	public List<ProcessInstance> getInstanceList(){
		return es.createProcessInstanceQuery().list();
	}
	
	public List<ProcessDefinition> getDefinitionList(){
		return rs.createProcessDefinitionQuery().list();
	}
	
	public List<Task> getTaskList(String user){
		return ts.findPersonalTasks(user);
	}
}
